package com.social.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSON;
import com.social.pojo.Changes;
import com.social.pojo.RegistrationOfCases;
import com.social.pojo.Ultimate;
import com.social.pojo.User;
import com.social.service.ChangesService;
import com.social.service.RegistraionOfCasesService;
import com.social.service.UltimateService;
import com.social.util.JsonUtil;
import com.social.util.ObjectUtil;
import com.social.util.PageUtil;
import com.social.util.StatusUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.social.util.ObjectUtil.getAge;
import static com.social.util.StatusUtil.getChanges;

/**
 * RegistraionOfCasses 来案登记模块(科长审核除外)
 */
@Controller
@RequestMapping("registraionOfCases")
public class RegistraionOfCassesController {
    /**
     * RegistraionOfCases service层对象
     */
    @Autowired
    private RegistraionOfCasesService registraionOfCasesService;
    /**
     * Changes service层对象
     */
    @Autowired
    private ChangesService changeService;
    /**
     * Ultimate service层对象
     */
    @Autowired
    private UltimateService ultimates;

    /**
     * 案件分页查询
     *
     * @param typeStatus     类型状态 (1、立案登记 2、日常审批 3、专项审批)
     * @param approvalStatus 审批状态 (0：提交未审批，1：审批通过，2：审批未通过，3：结案归档,4:立案未提交);
     * @param page           当前页
     * @param pageNum        每页显示条数
     * @param session        作用域
     * @param status         跳转页面状态
     * @return 页面
     */
    @RequestMapping("caseRegistrationPage")
    public String caseRegistrationPage(Integer typeStatus, Integer approvalStatus, Integer page, Integer pageNum, HttpSession session, Integer status) {
        //状态方法
        Map<String, Integer> mapStatus = StatusUtil.status(typeStatus, approvalStatus);
        //获取状态
        Integer status1 = mapStatus.get("typeStatus");
        Integer status2 = mapStatus.get("approvalStatus");
        //所有条数
        Integer count = registraionOfCasesService.caseRegistrationCount(null, null, null, status1, status2);
        //分页方法
        Map<String, Integer> util = PageUtil.page(pageNum, page, count);
        Integer pages = util.get("page");
        Integer num = util.get("pageNum");
        Integer remaining_pages = util.get("remaining_pages");
        Integer counts = util.get("count");
        //分页数据
        List<RegistrationOfCases> registrationOfCases = registraionOfCasesService.caseRegistrationPage(status1, status2, pages, num);
        Map<String, Object> map = new HashMap<String, Object>();
        //存入分页数据
        map.put("num", remaining_pages);
        map.put("page", pages);
        map.put("count", counts);
        //存入map集合
        session.setAttribute("map", map);
        //存入分页后的数据
        session.setAttribute("data", registrationOfCases);
        //根据状态返回页面
        return StatusUtil.statusYe(status);
    }

    /**
     * 案件模糊查询
     *
     * @param unitName           单位名称
     * @param organizationalCode 组织机构代码
     * @param nameOfRegistrant   登记人姓名
     * @param page               当前页
     * @param pageNum            每页显示条数
     * @param session            作用域
     * @param status             跳转页面状态
     * @param typeStatus         类型状态 (1、立案登记 2、日常审批 3、专项审批)
     * @param approvalStatus     审批状态 (0：提交未审批，1：审批通过，2：审批未通过，3：结案归档,4:立案未提交);
     * @return 页面
     */
    @RequestMapping("caseRegistrationLike")
    public String caseRegistrationLike(String unitName, String organizationalCode, String nameOfRegistrant, Integer page, Integer pageNum, HttpSession session, Integer status, Integer typeStatus, Integer approvalStatus) {
        //状态方法
        Map<String, Integer> likeStatus = StatusUtil.status(typeStatus, approvalStatus);
        //获取状态
        Integer status1 = likeStatus.get("typeStatus");
        Integer status2 = likeStatus.get("approvalStatus");
        //所有条数
        Integer count = registraionOfCasesService.caseRegistrationCount("%" + unitName + "%", "%" + nameOfRegistrant + "%", "%" + organizationalCode + "%", status1, status2);
        //分页方法
        Map<String, Integer> util = PageUtil.page(pageNum, page, count);
        Integer pages = util.get("page");
        Integer num = util.get("pageNum");
        Integer remaining_pages = util.get("remaining_pages");
        Integer counts = util.get("count");
        //分页数据
        List<RegistrationOfCases> registrationOfCasess = registraionOfCasesService.caseRegistrationLike("%" + unitName + "%", "%" + nameOfRegistrant + "%", "%" + organizationalCode + "%", status1, status2, pages, num);
        //模糊查询
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nums", remaining_pages);
        map.put("pages", pages);
        map.put("counts", counts);
        //存入map集合
        session.setAttribute("map", map);
        //存入分页数据
        session.setAttribute("data", registrationOfCasess);
        //存入前台请求的模糊查询字段（分页使用）
        session.setAttribute("unitName", unitName);
        session.setAttribute("organizationalCode", organizationalCode);
        session.setAttribute("nameOfRegistrant", nameOfRegistrant);
        //根据状态返回页面
        return StatusUtil.statusYe(status);
    }

    /**
     * 根据案件主键查询
     *
     * @param id registraionOfCases表主键id
     * @return 查询后的数据
     */
    @RequestMapping(value = "selectById", produces = "text/application;charset=utf-8")
    @ResponseBody
    public String selectById(Integer id) {
        RegistrationOfCases registrationOfCases = registraionOfCasesService.selectByPrimaryKey(id);
        return JSON.toJSONString(registrationOfCases);
    }

    /**
     * 来案登记添加  (typeStatus:1 approvalStatus:4)
     * 日常审计添加  (typeStatus:2,approvalStatus:0)
     *
     * @param registrationOfCases 实体对象
     * @return 操作结果状态
     */
    @RequestMapping(value = "insert", produces = "text/Application;charset=UTF-8")
    @ResponseBody
    public String insert(RegistrationOfCases registrationOfCases, HttpSession session) {
        //获取操作人
        User user = (User) session.getServletContext().getAttribute("user");
        registrationOfCases.setNameOfTheFiler(user.getRealName());
        //返回数据
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setStatus("身份证号重复");
        List<RegistrationOfCases> registrationOfCases2 = registraionOfCasesService.selectAll();
        for (RegistrationOfCases ofCases : registrationOfCases2) {
            if (registrationOfCases.getIdCard().equals(ofCases.getIdCard())) {
                return JSON.toJSONString(jsonUtil.getStatus());
            }
        }
        //根据身份证号获取年龄
        String age = getAge(registrationOfCases.getIdCard());
        registrationOfCases.setAge(Integer.valueOf(age));
        //调用插入数据方法
        int status = registraionOfCasesService.insert(registrationOfCases);
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        //返回插入状态
        return JSON.toJSONString(restates);
    }



    /**
     * 案件修改状态
     *
     * @param registrationOfCases 实体对象
     * @return registrationOfCases primary key
     */
    @RequestMapping("updateStatus")
    @ResponseBody
    public String updateStatus(RegistrationOfCases registrationOfCases) {
        //id
        Integer id = registrationOfCases.getId();
        if (registrationOfCases.getApprovalStatus() != null) {
            if (registrationOfCases.getWarningTime() == null) registrationOfCases.setWarningTime(1);
            //立案审批通过
            registraionOfCasesService.updateByPrimaryKeySelective(registrationOfCases);
            //根据主键id查询
            RegistrationOfCases registrationOfCasess = registraionOfCasesService.selectByPrimaryKey(registrationOfCases.getId());
            if (registrationOfCases.getApprovalStatus() == 1) {
                //添加科长审批数据
                Ultimate ultimate = ObjectUtil.getUltimate(registrationOfCasess);
                //查询是否有数据重复
                Ultimate queryUltimate = ultimates.selectByPrimaryKey(registrationOfCases.getId());
                if (queryUltimate == null) {
                    ultimates.insertSelective(ultimate);
                } else {
                    ultimates.updateByPrimaryKeySelective(ultimate);
                }
            }
        }
        return JSON.toJSONString(id);
    }

    /**
     * 案件登记修改,日常审计修改（模态框）
     *
     * @param registrationOfCases 实体对象
     * @param change              实体对象
     * @return 修改状态
     */
    @RequestMapping(value = "update", produces = "text/Application;charset=UTF-8")
    @ResponseBody
    public String update(RegistrationOfCases registrationOfCases, Changes change, HttpSession session) {
        //修改操作 动态sql
        int status = registraionOfCasesService.updateByPrimaryKeySelective(registrationOfCases);
        //返回数据
        JsonUtil jsonUtil = new JsonUtil();
        //判断操作成功 并且 操作人不为null执行
        if (status == 1 && registrationOfCases.getNameOfRegistrant() != null) {
            //获取操作人
            User user = (User) session.getServletContext().getAttribute("user");
            Changes changes = getChanges("修改", registrationOfCases.getId(), registrationOfCases.getUnitName(), registrationOfCases.getPhone(), status, user.getRealName(), change);
            //添加方法
            changeService.insertSelective(changes);
        }
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        //返回修改状态
        return JSON.toJSONString(restates);
    }

    /**
     * 案件的登记数据删除,日常审计数据删除 (将type_status改成0)
     *
     * @param id               registrationOfCases primary key
     * @param change           实体对象
     * @param nameOfRegistrant 登记人姓名
     * @param unitName         单位名称
     * @param phone            联系电话
     * @return 删除状态
     */
    @RequestMapping("delete")
    @ResponseBody
    public String delete(Integer id, Changes change, String nameOfRegistrant, String unitName, String phone, HttpSession session) {
        //删除操作
        int status = registraionOfCasesService.deleteByPrimaryKey(id);
        if (status == 1 && nameOfRegistrant != null) {
            //获取操作人
            User user = (User) session.getServletContext().getAttribute("user");
            //调用删除记录方法
            Changes changes = getChanges("删除", id, unitName, phone, status, user.getRealName(), change);
            changeService.insertSelective(changes);
        }
        //返回数据
        JsonUtil jsonUtil = new JsonUtil();
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        return JSON.toJSONString(restates);
    }

    /**
     * 批量删除
     *
     * @param id     registrationOfCases primary key
     * @param status 跳转controller状态
     * @return controller
     */
    @RequestMapping("bulkDelete")
    public String bulkDelete(String id, Integer status) {
        List<Integer> list = new ArrayList<Integer>();
        String[] strs = id.split(",");
        for (int i = 0; i < strs.length; i++) {
            list.add(Integer.parseInt(strs[i]));
            registraionOfCasesService.bulkDelete(list);
        }
        return StatusUtil.statusController(status);
    }

    /**
     * 批量导出
     *
     * @param map 集合
     * @param id  registraionOfCases primary key
     * @return controller
     */
    @RequestMapping("bulkExport")
    public String bulkExport(ModelMap map, String id) {
        String[] strs = id.split(",");
        ArrayList<RegistrationOfCases> registrationOfCasess = new ArrayList<>();
        for (int i = 0; i < strs.length; i++) {
            Integer[] ids = new Integer[]{Integer.valueOf(strs[i])};
            List<RegistrationOfCases> registrationOfCases = registraionOfCasesService.bulkExport(ids);
            registrationOfCasess.addAll(registrationOfCases);
        }
        ExportParams exportParams = new ExportParams("管理", "案件所有数据", ExcelType.XSSF);
        //导出的集合
        map.put(NormalExcelConstants.DATA_LIST, registrationOfCasess);
        map.put(NormalExcelConstants.CLASS, RegistrationOfCases.class);
        map.put(NormalExcelConstants.PARAMS, exportParams);
        map.put(NormalExcelConstants.FILE_NAME, "案件导出的数据");
        return "easypoiExcelView";
    }

    /**
     * 批量导入
     *
     * @param file    导入的文件
     * @param session 作用域
     * @return
     * @throws Exception 文件找不到或路径找不到
     */
    @RequestMapping("bulkImport")
    @ResponseBody
    public String bulkImport(MultipartFile file, HttpSession session) throws Exception {
        //操作状态
        int status = 0;
        try {
            //后缀名
            String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //文件路径
            File files = new File(session.getServletContext().getRealPath("/importFile/"));
            //判断文件夹是否存在
            if (!files.exists()) {
                files.mkdirs();
            }
            //随机数
            double v = Math.random() * 100;
            //时间戳
            String yyyyMMddHH = new SimpleDateFormat("yyyyMMddHH").format(new Date());
            //设置文件上传路径并将文件名设置进去
            file.transferTo(new File(files, (int) v + yyyyMMddHH + fileName));
            //创建导入对象
            ImportParams params = new ImportParams();
            params.setTitleRows(1); //表格标题行数,默认0
            params.setHeadRows(1);  //表头行数,默认1

            //获取导入数据
            List<RegistrationOfCases> teachers = ExcelImportUtil.importExcel(new FileInputStream(new File(files + "/" + (int) v + yyyyMMddHH + fileName)), RegistrationOfCases.class, params);
            for (RegistrationOfCases teacher : teachers) {
                RegistrationOfCases registrationOfCases = registraionOfCasesService.selectByPrimaryKey(teacher.getId());
                if (registrationOfCases == null) {
                    status = registraionOfCasesService.insertSelective(teacher);
                } else {
                    status = registraionOfCasesService.updateByPrimaryKeySelective(teacher);
                }
            }
        } catch (Exception e) {
            JsonUtil jsonUtil = new JsonUtil();
            jsonUtil.setCode("请选择正确的文件");
            return JSON.toJSONString(jsonUtil.getCode());
        }
        //返回数据
        JsonUtil jsonUtil = new JsonUtil();
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        return JSON.toJSONString(restates);
    }
}